package com.bw.producer.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.factory.Factory.Payment;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.bw.common.core.domain.Result;
import com.bw.common.core.utils.sign.Base64;
import com.bw.producer.Vo.AliPay;
import com.bw.producer.config.AliConfig;
import com.bw.producer.config.AliPayConfig;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

//@RestController
//@RequestMapping("aliPay")
//@AllArgsConstructor
//public class AliPayController {
//
//    private final AliConfig getConfig;
//
//    @GetMapping("aliPay")
//    public Result aliPay() throws Exception {
//        String num = String.valueOf(new Random().nextInt(900000 - 100000));
//        Factory.setOptions(getConfig.getConfig());
//        AlipayTradePrecreateResponse response = Payment.FaceToFace().preCreate("华为mate 20", num, "8888.88");
//        JSONObject jsonObject = JSON.parseObject(response.httpBody);
//        JSONObject newJsonObject = jsonObject.getJSONObject("alipay_trade_precreate_response");
//        String qrCode = newJsonObject.getString("qr_code");
//
//        QrConfig config = new QrConfig(400,400);
//        BufferedImage generate = QrCodeUtil.generate(qrCode, config);
//
//        HashMap<String, Object> map = new HashMap<>();
//        // 转换流信息写出
//        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
//        try
//        {
//            ImageIO.write(generate, "jpg", os);
//        }
//        catch (IOException e)
//        {
//            return Result.error(e.getMessage());
//        }
//
//        map.put("img", Base64.encode(os.toByteArray()));
//        return Result.success(map);
//    }
//
//    @GetMapping("config")
//    public void config() {
//        System.out.println("支付成功");
//    }

    @RestController
    @RequestMapping("alipay")
    @Transactional(rollbackFor = Exception.class)
    public class AliPayController {

        @Resource
        AliPayConfig aliPayConfig;


        private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
        private static final String FORMAT ="JSON";
        private static final String CHARSET ="utf-8";
        private static final String SIGN_TYPE ="RSA2";

        @GetMapping("/pay") // 前端路径参数格式?subject=xxx&traceNo=xxx&totalAmount=xxx
        public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());
            request.setReturnUrl(aliPayConfig.getReturnUrl());
            request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                    + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                    + "\"subject\":\"" + aliPay.getSubject() + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            String form = "";
            try {
                // 调用SDK生成表单
                form = alipayClient.pageExecute(request).getBody();
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            // 直接将完整的表单html输出到页面
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        }

        @PostMapping("/notify")  // 注意这里必须是POST接口
        public String payNotify(HttpServletRequest request) throws Exception {
            if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
                System.out.println("=========支付宝异步回调========");

                Map<String, String> params = new HashMap<>();
                Map<String, String[]> requestParams = request.getParameterMap();
                for (String name : requestParams.keySet()) {
                    params.put(name, request.getParameter(name));
                }

                //订单号
                String tradeNo = params.get("out_trade_no");
                // 支付时间
                String gmtPayment = params.get("gmt_payment");
                // 支付宝交易凭证号
                String alipayTradeNo = params.get("trade_no");

                // 支付宝验签
                if (Factory.Payment.Common().verifyNotify(params)) {
                    // 验签通过
                    System.out.println("交易名称: " + params.get("subject"));
                    System.out.println("交易状态: " + params.get("trade_status"));
                    System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                    System.out.println("商户订单号: " + params.get("out_trade_no"));
                    System.out.println("交易金额: " + params.get("total_amount"));
                    System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                    System.out.println("买家付款时间: " + params.get("gmt_payment"));
                    System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                    // 更新订单已支付的逻辑代码
                    //todo

                }
            }
            return "success";
        }

    }
